package com.dailyblue.java.spring.cloud.example.sentinel.customer.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.spring.cloud.example.commons.util.JsonResult;
import com.dailyblue.java.spring.cloud.example.commons.util.ResultCode;
import com.dailyblue.java.spring.cloud.example.commons.util.ResultTool;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class GlobalExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        JsonResult result;
        if (e instanceof FlowException) {
            result = ResultTool.fail(401, "你的访问被限流了！");
        } else if (e instanceof AuthorityException) {
            result = ResultTool.fail(402, "你的访问权限不足！");
        } else {
            result = ResultTool.fail(ResultCode.COMMON_FAIL);
        }
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(JSONArray.toJSONString(result));
    }
}
